<template>
  <div>
    <ul class="list">
      <li class="item" v-for="item of touch" :key="item" @click="handleClick" :ref="item"
       @touchstart.prevent="handleTouchStart"
       @touchmove="handleTouchMove"
       @touchend="handleTouchEnd"
      >{{item}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'CityAlpha',
  props: {
    cities: Object
  },
  data () {
    return {
      touchFlag: false,
      startY: 0,
      timer: null,
      index: 0
    }
  },
  update () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchFlag = true
    },
    handleTouchMove (e) {
      if (this.touchFlag) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setInterval(() => {
          const touchY = e.touches[0].clientY - 150
          const index = Math.floor((touchY - this.startY) / 20)
          this.index = index
          if (index >= 0 && this.touch.length) {
            this.$emit('change', this.touch[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchFlag = false
    }
  },
  computed: {
    touch () {
      const touch = []
      for (let i in this.cities) {
        touch.push(i)
      }
      return touch
    }
  }
}
</script>

<style lang="stylus" scoped>
 @import '~styles/varibles.styl'
 .list
  display: flex
  flex-direction: column
  justify-content: center
  position: absolute
  top: 1.4rem
  right: 0
  bottom: 0
  width: .4rem
  .item
   line-height: .4rem
   text-align: center
   color: $bgColor
</style>
